package com.jwgf.smarowindingmachine_unity.ui;

import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jwgf.common.ViewCache;
import com.jwgf.faultnavigation.FaultNavigationMap;
import com.jwgf.fram.FramManager;
import com.jwgf.fram.FramManager.OnFramChangedListener;
import com.jwgf.group.GroupMap;
import com.jwgf.objectbox.ObjectBox;
import com.jwgf.objectbox.SpindleParameter;
import com.jwgf.smarowindingmachine_unity.R;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;
import com.jwgf.smarowindingmachine_unity.logic.Report;
import com.jwgf.smarowindingmachine_unity.logic.UnitUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

public class MachineStateSpindleStateFragment extends BaseFragment implements OnClickListener {

    public static final String fragmentTag = "MachineStateSpindleStateFragment";
    private View v;
    private GifSurfaceView gifContainer;
    private ImageView pngContainer;
    private TextView txtSpeed;
    private TextView txtlength;
    private TextView txtweight;
    private TextView txtsetlength;
    private TextView txtsetweight;
    private TextView txtSpindle;
    private TextView pkg_current_len_unit;
    private TextView pkg_set_len_unit;
    private TextView pkg_current_wei_unit;
    private TextView pkg_set_wei_unit;
    private Button btn_ss_prev;
    private Button btn_ss_next;
    private int currentSpindleNumber, maxSpindleNumber;
    private String value1, value2;
    private int grp_select;

    private BitSet bitSet1 = new BitSet();
    private BitSet bitSet2 = new BitSet();

    private FramManager fm = FramManager.getInstance();
    private MachineParameterSharedPreference sp = MachineParameterSharedPreference.getInstance();

    private int spindleErrorArrayVCRO[][] = {
            {0, R.drawable.spindle_error_00_vcro},//筒纱打结数超过上限
            {0, R.drawable.spindle_error_01_vcro},//管纱切纱次数达到上限
            {0, R.drawable.spindle_error_02_vcro},//捻接循环次数达到上限
            {0, R.drawable.spindle_error_03_vcro},//筒纱吸嘴吸纱次数达到上限
            {0, R.drawable.spindle_error_04_vcro},//换管次数达到上限
            {0, R.drawable.spindle_error_05},//筒纱吸嘴纱线传感器故障信号
            {0, R.drawable.spindle_error_06_vcro},//换管电机零位传感器故障
            {0, R.drawable.spindle_error_07_vcro},//管纱吸嘴零位传感器故障
            {0, R.drawable.spindle_error_08_vcro},//捻结器电机零位传感器故障
            {0, R.drawable.spindle_error_09_vcro},//支臂测速传感器故障信号
            {0, R.drawable.spindle_error_10_vcro},//无刷电机测速霍尔故障
            {0, R.drawable.spindle_error_11_vcro},//无刷电机驱动器故障
            {0, R.drawable.spindle_error_12_vcro},//筒纱直径与实际不符
            {0, R.drawable.spindle_error_13_vcro},//防缠绕开关信号
            {0, R.drawable.spindle_error_14_vcro},//筒纱嘴零位传感器故障信号
            {0, R.drawable.spindle_error_15_vcro},//捻结等待超时
            {0, R.drawable.spindle_error_16_vcro}//张力传感器报警
    };

    private int spindleErrorArrayVCROM[][] = {
            {0, R.drawable.spindle_error_00_vcrom},//筒纱打结数超过上限
            {0, R.drawable.spindle_error_01_vcrom},//管纱切纱次数达到上限
            {0, R.drawable.spindle_error_02_vcrom},//捻接循环次数达到上限
            {0, R.drawable.spindle_error_03_vcrom},//筒纱吸嘴吸纱次数达到上限
            {0, R.drawable.spindle_error_04_vcrom},//换管次数达到上限
            {0, R.drawable.spindle_error_05},//筒纱吸嘴纱线传感器故障信号
            {0, R.drawable.spindle_error_06_vcrom},//换管电机零位传感器故障
            {0, R.drawable.spindle_error_07_vcrom},//管纱吸嘴零位传感器故障
            {0, R.drawable.spindle_error_08_vcrom},//捻结器电机零位传感器故障
            {0, R.drawable.spindle_error_09_vcrom},//支臂测速传感器故障信号
            {0, R.drawable.spindle_error_10_vcrom},//无刷电机测速霍尔故障
            {0, R.drawable.spindle_error_11_vcrom},//无刷电机驱动器故障
            {0, R.drawable.spindle_error_12_vcrom},//筒纱直径与实际不符
            {0, R.drawable.spindle_error_13_vcrom},//防缠绕开关信号
            {0, R.drawable.spindle_error_14_vcrom},//筒纱嘴零位传感器故障信号
            {0, R.drawable.spindle_error_15_vcrom},//捻结等待超时
            {0, R.drawable.spindle_error_16_vcrom}//张力传感器报警
    };


    OnFramChangedListener listener = new OnFramChangedListener() {
        @Override
        public void onFramChanged(FramManager framManager, String key) {
            if (key.equals(currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 1) ||
                    key.equals(currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 2)) {
                currentSpindleNumber = Integer.valueOf(sp.getValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER));
                value1 = currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 1;
                value2 = currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 2;
                if (key.equals(String.valueOf(value1)) || key.equals(String.valueOf(value2))) {
                    refreshView();
                }
            }
            if (key.equals(currentSpindleNumber + "-" + (0x60 & 0xff) + "-" + 0)) {

                int curLengthValue = UnitUtils.pulse2Length(Report.getInstance().getCurrentPulse(currentSpindleNumber), currentSpindleNumber);
                String curUILengthValue = UnitUtils.getUILength(String.valueOf(curLengthValue));
                txtlength.setText(curUILengthValue);
                grp_select = GroupMap.getInstance().getSpindleGroupNo(currentSpindleNumber);
                long id = GroupMap.getInstance().getSpindleParameterIdFromGroup(grp_select);
                SpindleParameter para = ObjectBox.get().boxFor(SpindleParameter.class).get(id);
                String pkg_wei_value = UnitUtils.getUIWeightFromLength(curLengthValue, para);
                txtweight.setText(pkg_wei_value);

            }

        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = ViewCache.getInstance().getView(R.layout.fragment_machine_state_spindle_state);
        initView();
        refreshView();
        return v;
    }

    protected void clearSpindleErrorList() {
        for (int i = 0; i < 17; i++) {
            spindleErrorArrayVCRO[i][0] = 0;
            spindleErrorArrayVCROM[i][0] = 0;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            gifContainer.setVisibility(View.INVISIBLE);
            fm.unregisterOnFramChangedListener(listener);
        } else {
            fm.registerOnFramChangedListener(listener);
            gifContainer.setVisibility(View.VISIBLE);
            currentSpindleNumber = Integer.valueOf(sp.getValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER));
            refreshView();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btn_ss_prev:
                if (currentSpindleNumber > 1) {
                    currentSpindleNumber--;
                    sp.setValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER, String.valueOf(currentSpindleNumber));
                    refreshView();
                } else {
                    currentSpindleNumber = maxSpindleNumber;
                    sp.setValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER, String.valueOf(currentSpindleNumber));
                    refreshView();
                }
                break;
            case R.id.btn_ss_next:
                if (currentSpindleNumber < maxSpindleNumber) {
                    currentSpindleNumber++;
                    sp.setValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER, String.valueOf(currentSpindleNumber));
                    refreshView();
                } else {
                    currentSpindleNumber = 1;
                    sp.setValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER, String.valueOf(currentSpindleNumber));
                    refreshView();
                }
                break;
        }
    }

    public void initView() {
        txtSpeed = (TextView) v.findViewById(R.id.txtSpeed);
        txtlength = (TextView) v.findViewById(R.id.txtlength);
        txtweight = (TextView) v.findViewById(R.id.txtweight);
        txtsetlength = (TextView) v.findViewById(R.id.txtsetlength);
        txtsetweight = (TextView) v.findViewById(R.id.txtsetweight);
        txtSpindle = (TextView) v.findViewById(R.id.txtSpindle);
        btn_ss_prev = (Button) v.findViewById(R.id.btn_ss_prev);
        btn_ss_next = (Button) v.findViewById(R.id.btn_ss_next);
        btn_ss_prev.setOnClickListener(this);
        btn_ss_next.setOnClickListener(this);

        pkg_current_len_unit = (TextView) v.findViewById(R.id.txtlengthUnit);
        pkg_set_len_unit = (TextView) v.findViewById(R.id.txtsetlengthUnit);
        pkg_current_wei_unit = (TextView) v.findViewById(R.id.txtweightUnit);
        pkg_set_wei_unit = (TextView) v.findViewById(R.id.txtsetWeightUnit);


        FramManager fm = FramManager.getInstance();
        fm.registerOnFramChangedListener(listener);
        currentSpindleNumber = Integer.valueOf(sp.getValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER));

        gifContainer = (GifSurfaceView) v.findViewById(R.id.spindle_gif_container);
        gifContainer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bitSet1.cardinality() != 0) {
                    int code = 0x630100 | bitSet1.nextSetBit(0);
                    EventBus.getDefault().post(FaultNavigationMap.getInstance().get(code));
                } else if (bitSet2.cardinality() != 0) {
                    int code = 0x630200 | bitSet2.nextSetBit(0);
//                    Bus.getDefault().post(FaultNavigationMap.getInstance().get(code));
                }
            }
        });

        pngContainer = v.findViewById(R.id.png_container);
        pngContainer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bitSet1.cardinality() != 0) {
                    int code = 0x630100 | bitSet1.nextSetBit(0);
                    EventBus.getDefault().post(FaultNavigationMap.getInstance().get(code));
                } else if (bitSet2.cardinality() != 0) {
                    int code = 0x630200 | bitSet2.nextSetBit(0);
//                    Bus.getDefault().post(FaultNavigationMap.getInstance().get(code));
                }
            }
        });

    }

    private void refreshView() {
        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_LENGTH_UNIT, "0").equals("0")) {
            pkg_current_len_unit.setText(R.string.ss_lengthUnit);
            pkg_set_len_unit.setText(R.string.ss_lengthUnit);
        } else {
            pkg_current_len_unit.setText(R.string.behind_y);
            pkg_set_len_unit.setText(R.string.behind_y);
        }
        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_WEIGHT_UNIT, "0").equals("0")) {
            pkg_current_wei_unit.setText(R.string.ss_weightUnit);
            pkg_set_wei_unit.setText(R.string.ss_weightUnit);
        } else {
            pkg_current_wei_unit.setText(R.string.ss_weightUnit_eng);
            pkg_set_wei_unit.setText(R.string.ss_weightUnit_eng);
        }
        maxSpindleNumber = Integer.parseInt(sp.getValue(0x29, 0x01));
        currentSpindleNumber = Integer.valueOf(sp.getValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER));
        if (currentSpindleNumber > maxSpindleNumber) {
            currentSpindleNumber = maxSpindleNumber;
            sp.setValue(MachineParameterSharedPreference.CURRENT_SPINDLE_NUMBER, String.valueOf(currentSpindleNumber));
        }
        String title = getString(R.string.ss_title) + " " + currentSpindleNumber;
        txtSpindle.setText(title);
        grp_select = GroupMap.getInstance().getSpindleGroupNo(currentSpindleNumber);
        long id = GroupMap.getInstance().getSpindleParameterIdFromGroup(grp_select);
        SpindleParameter para = ObjectBox.get().boxFor(SpindleParameter.class).get(id);
        txtSpeed.setText(para.frame20DB);
        int curLengthValue = UnitUtils.pulse2Length(Report.getInstance().getCurrentPulse(currentSpindleNumber), currentSpindleNumber);
        String curUILengthValue = UnitUtils.getUILength(String.valueOf(curLengthValue));
        txtlength.setText(curUILengthValue);
        String pkg_wei_value = UnitUtils.getUIWeightFromLength(curLengthValue, para);
        txtweight.setText(pkg_wei_value);
        float pkg_len_value = Float.parseFloat(para.frame24DB);
        txtsetlength.setText(UnitUtils.getUILength(String.valueOf(pkg_len_value)));
        String pkg = UnitUtils.getUIWeightFromLength(Integer.parseInt(para.frame24DB), para);
        txtsetweight.setText(pkg);

        clearSpindleErrorList();

        String key0 = currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 1;
        String key1 = currentSpindleNumber + "-" + (0x63 & 0xff) + "-" + 2;
        int dc = fm.getInt(key0, 0);
        bitSet1.clear();
        bitSet2.clear();
        for (int i = 0; i < 16; i++) {
            int bit = (dc >> i) & 0x01;
            if (bit != 0) {
                spindleErrorArrayVCRO[i][0] = 1;
                spindleErrorArrayVCROM[i][0] = 1;
                if (!(i == 0 || i == 1 || i == 5 || i == 0xC || i == 0xD || i == 0xF)) {
                    if (bitSet1.cardinality() == 0) {
                        bitSet1.set(i);
                    }
                }
            }
        }
        int dd = fm.getInt(key1, 0);
        int bit = (dd >> 3) & 0x01;
        if (bit != 0) {
            spindleErrorArrayVCRO[16][0] = 1;
            spindleErrorArrayVCROM[16][0] = 1;
            if (bitSet2.cardinality() == 0) {
                bitSet2.set(3);
            }
        }


        int mt = Integer.parseInt(sp.getValue(MachineParameterSharedPreference.MACHINE_MACHINE_TYPE, "0"));

        switch (mt) {
            case 0:
            case 1:
            case 4: {
                gifContainer.setVisibility(View.INVISIBLE);
                pngContainer.setVisibility(View.VISIBLE);
                ArrayList<Integer> list = new ArrayList<Integer>();
                list.add(R.drawable.spindle_error_bk_vcrom);
                for (int i = 0; i <= 16; i++) {
                    if (spindleErrorArrayVCROM[i][0] != 0) {
                        list.add(spindleErrorArrayVCROM[i][1]);
                    }
                }
                generateImage(list);
                break;
            }
            case 2:
            case 3:
            case 5: {
                gifContainer.setVisibility(View.VISIBLE);
                pngContainer.setVisibility(View.INVISIBLE);
                ArrayList<Integer> list = new ArrayList<Integer>();
                list.add(R.drawable.spindle_error_bk_vcro);
                for (int i = 0; i <= 16; i++) {
                    if (spindleErrorArrayVCRO[i][0] != 0) {
                        list.add(spindleErrorArrayVCRO[i][1]);
                    }
                }
                gifContainer.setMovieList(list);
                break;
            }
        }
    }

    private void generateImage(List<Integer> imageList) {
        Resources resources = getResources();
        Drawable[] layers = new Drawable[imageList.size()];
        for (int i = 0; i < imageList.size(); ++i) {
            layers[i] = resources.getDrawable(imageList.get(i));
        }
        LayerDrawable layerDrawable = new LayerDrawable(layers);
        pngContainer.setImageDrawable(layerDrawable);
    }

}
